package com.ling.recipeassistant.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ling.recipeassistant.data.model.Recipe
import com.ling.recipeassistant.data.repository.RecipeRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SearchViewModel @Inject constructor(
    private val recipeRepository: RecipeRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(SearchUiState())
    val uiState: StateFlow<SearchUiState> = _uiState.asStateFlow()
    
    // 分页相关参数
    private val pageSize = 10
    private var currentPage = 0
    private var allSearchResults = listOf<Recipe>()
    private var hasMoreData = true
    private var currentQuery = ""
    
    fun searchRecipes(query: String) {
        if (query.isBlank()) {
            _uiState.value = _uiState.value.copy(
                searchResults = emptyList(),
                isLoading = false,
                hasMoreData = false
            )
            return
        }
        
        // 如果查询词改变，重置分页
        if (currentQuery != query) {
            currentQuery = query
            currentPage = 0
            hasMoreData = true
            _uiState.value = _uiState.value.copy(
                searchResults = emptyList(),
                hasMoreData = true
            )
        }
        
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            try {
                // 从数据库搜索菜谱
                recipeRepository.searchRecipes(query).collectLatest { results ->
                    allSearchResults = results
                    hasMoreData = results.isNotEmpty()
                    
                    // 加载第一页
                    loadNextPage()
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "搜索失败",
                    isLoading = false
                )
            }
        }
    }
    
    fun loadNextPage() {
        if (!hasMoreData || _uiState.value.isLoadingMore) return
        
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingMore = true)
            try {
                val startIndex = currentPage * pageSize
                val endIndex = minOf(startIndex + pageSize, allSearchResults.size)
                
                if (startIndex < allSearchResults.size) {
                    val newRecipes = allSearchResults.subList(startIndex, endIndex)
                    val currentRecipes = _uiState.value.searchResults.toMutableList()
                    currentRecipes.addAll(newRecipes)
                    
                    currentPage++
                    hasMoreData = endIndex < allSearchResults.size
                    
                    _uiState.value = _uiState.value.copy(
                        searchResults = currentRecipes,
                        isLoading = false,
                        isLoadingMore = false,
                        hasMoreData = hasMoreData
                    )
                } else {
                    hasMoreData = false
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        isLoadingMore = false,
                        hasMoreData = false
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "加载更多搜索结果失败",
                    isLoading = false,
                    isLoadingMore = false
                )
            }
        }
    }
    
    fun searchByIngredients(ingredients: String) {
        if (ingredients.isBlank()) {
            _uiState.value = _uiState.value.copy(
                searchResults = emptyList(),
                isLoading = false,
                hasMoreData = false
            )
            return
        }
        
        // 重置分页
        currentPage = 0
        hasMoreData = true
        _uiState.value = _uiState.value.copy(
            searchResults = emptyList(),
            hasMoreData = true
        )
        
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            try {
                // 从数据库根据食材搜索
                val ingredientList = ingredients.split(",").map { it.trim() }
                val results = mutableListOf<Recipe>()
                
                // 对每个食材进行搜索
                ingredientList.forEach { ingredient ->
                    recipeRepository.getRecipesByIngredient(ingredient).collectLatest { recipes ->
                        results.addAll(recipes.filter { recipe ->
                            !results.any { it.id == recipe.id } // 避免重复
                        })
                    }
                }
                
                allSearchResults = results
                hasMoreData = results.isNotEmpty()
                
                // 加载第一页
                loadNextPage()
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "搜索失败",
                    isLoading = false
                )
            }
        }
    }
    
    fun clearSearch() {
        currentQuery = ""
        currentPage = 0
        hasMoreData = true
        allSearchResults = emptyList()
        _uiState.value = _uiState.value.copy(
            searchResults = emptyList(),
            error = null,
            hasMoreData = true
        )
    }
    
    // 收藏功能
    fun toggleFavorite(recipeId: String) {
        viewModelScope.launch {
            try {
                recipeRepository.toggleFavorite(recipeId)
                // 重新搜索以更新收藏状态
                if (currentQuery.isNotBlank()) {
                    searchRecipes(currentQuery)
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = e.message ?: "收藏操作失败"
                )
            }
        }
    }
    
    fun clearError() {
        _uiState.value = _uiState.value.copy(error = null)
    }
}

data class SearchUiState(
    val searchResults: List<Recipe> = emptyList(),
    val isLoading: Boolean = false,
    val isLoadingMore: Boolean = false,
    val hasMoreData: Boolean = true,
    val error: String? = null
) 